package com.gatling_node;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Random;
import java.util.TimeZone;

public class Utils {
    private static final String ENCODING = "UTF-8";
    private static final String MAC_NAME = "HmacSHA1";
    private static final String SIGNATURE_APP_SECRET = "TTZaK2rpkB80tnyTHpkW1wHp4M1Z7IcX";
    private static final String androidId = "xxyy_android";

    public static String buildSignatureSocketUrl(String token,String serviceVersion) {
        StringBuilder childPath = new StringBuilder();
        childPath.append("/")
                .append(token).append("/")
                .append(androidId)
                .append("/android/")
                .append(serviceVersion)
                .append("/")
                .append(androidId)
                .append("/")
                .append(getRandomString(32)).append("/")
                .append(getUTCTimeStr());
        try {
            String encode = URLEncoder.encode(childPath.toString(), "utf-8");
            String signature = HmacSHA1Encrypt(encode, SIGNATURE_APP_SECRET);
            childPath.append("/").append(signature);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(childPath.toString());
        return childPath.toString();
    }

    public static String HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);

        byte[] text = encryptText.getBytes(ENCODING);
        // 完成 Mac 操作
        byte[] result = mac.doFinal(text);
        return byte2hex(result);
    }

    public static String md5(String string) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static String getRandomString(int length) {
        //1.  定义一个字符串（A-Z，a-z，0-9）即62个数字字母；
        String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        //2.  由Random生成随机数
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        //3.  长度为几就循环几次
        for (int i = 0; i < length; ++i) {
            //从62个的数字或字母中选择
            int number = random.nextInt(62);
            //将产生的数字通过length次承载到sb中
            sb.append(str.charAt(number));
        }
        sb.append(System.currentTimeMillis());
        sb.append(androidId);
        //将承载的字符转换成字符串
        return md5(sb.toString());
    }

    public static String getUTCTimeStr() {
        Calendar cal = Calendar.getInstance();
        TimeZone tz = TimeZone.getTimeZone("GMT");
        cal.setTimeZone(tz);
        return String.valueOf(cal.getTimeInMillis() / 1000);// 返回的UTC时间戳
    }

    //二行制转字符串
    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString();
    }
}

